package com.whsm.admin.controller;

import com.whsm.admin.domain.City;
import com.whsm.admin.domain.User;
import com.whsm.admin.domain.User1;
import com.whsm.admin.service.CityService;
import com.whsm.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class IndexController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    UserService userService;

    @Autowired
    CityService cityService;

    @GetMapping(value = {"/","/login"})
    public String loginPage(){
        return "login";
    }

    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model){
        if (StringUtils.hasLength(user.getUsername()) && "123456".equals(user.getPassword())){
            session.setAttribute("loginUser",user);
            return "redirect:main.html";
        }else {
            model.addAttribute("msg","密码或账号错误");
            return "login";
        }

    }

    @GetMapping("/main.html")
    public String mainPage(HttpSession session,Model model){
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null){
            return "main";
        }else {
            model.addAttribute("msg","您未登录请先登陆！");
            return "login";
        }
    }
    @GetMapping("/error500")
    public void error500(){
        int i = 1/0;
    }

    @GetMapping("/defaulterror")
    public void error(){
        String name = null;
        System.out.println(name.length());
    }

    @GetMapping("/sql")
    @ResponseBody
    public String save(){
        Integer integer = jdbcTemplate.queryForObject("select count(*) from user", Integer.class);
        String s = integer.toString();
        return s;
    }
    @GetMapping("/find")
    @ResponseBody
    public User1 returnUser(String id){
        int i = Integer.parseInt(id);
        User1 userById = userService.getUserById(i);
        return userById;
    }

    @GetMapping("/findCity")
    @ResponseBody
    public City getCity(@RequestParam("id") String idl){

        City city = cityService.getCity(Long.parseLong(idl));
        return city;
    }
}
